/*	BuildMachineShop class definition.
 *
*/

#include "BuildingPlacer.h"
#include "BuildMachineShop.h"

void BuildMachineShop::Enter()
{
	DEBUG_PRINT("BuildMachineShop(%p) %s entering\n", this, GetName().c_str());

}

void BuildMachineShop::Execute()
{
	DEBUG_PRINT("BuildMachineShop(%p) %s executing\n", this, GetName().c_str());
	std::list<Base*>* bases = BB->GetBases();
	std::list<BWAPI::Unit*>* factories;
	BWAPI::Unit* fac = NULL;
	for(std::list<Base*>::iterator base = bases->begin(); base != bases->end() && !fac; base++)
	{
		factories = (*base)->GetBuildingsByType(BWAPI::UnitTypes::Terran_Factory);
		if(factories)
		{
			for(std::list<BWAPI::Unit*>::iterator it = factories->begin(); it != factories->end(); it++)
			{
				if(!(*it)->getAddon())
				{
					fac = (*it);
					break;
				}
			}
		}
	}
	if(fac)
	{
		fac->buildAddon(BWAPI::UnitTypes::Terran_Machine_Shop);
		BB->SpendResources(BWAPI::UnitTypes::Terran_Machine_Shop);
	}
	control->FinishWithSuccess();
}

void BuildMachineShop::Exit()
{
	DEBUG_PRINT("BuildMachineShop(%p) %s exiting\n", this, GetName().c_str());
	
}

bool BuildMachineShop::CheckConditions()
{
	DEBUG_PRINT("BuildMachineShop(%p) %s checking conditions\n", this, GetName().c_str());
	
	std::list<BWAPI::Unit*>* fac = BB->GetBuildingsByTypeGeneral(BWAPI::UnitTypes::Terran_Factory);
	std::list<BWAPI::Unit*>* shop = BB->GetBuildingsByTypeGeneral(BWAPI::UnitTypes::Terran_Machine_Shop);
	if(fac)
	{
		if(!shop)
		{
			if(BB->isBuildBuilding(BWAPI::UnitTypes::Terran_Machine_Shop) )
			{
				DEBUG_PRINT("BuildMachineShop(%p) %s checked conditions and has %d minerals to spend\n", this, GetName().c_str(), BB->GetMineralsToSpend());
				return true;
			}
		}
		else if(shop->size() < fac->size())
		{
			if(BB->isBuildBuilding(BWAPI::UnitTypes::Terran_Machine_Shop) )
			{
				DEBUG_PRINT("BuildMachineShop(%p) %s checked conditions and has %d minerals to spend\n", this, GetName().c_str(), BB->GetMineralsToSpend());
				return true;
			}
		}

	}
	

	return false;
}